<template>
  <div class="pickcar">
    <my-head title="下线收车" :isRightClick = "true"/>

    <mu-text-field v-show="isShowVin" v-model="vin" placeholder="VIN" ref="vin" class='input' @keyup.enter.native="getVin()"><i class="iconfont icon-saomiao" @click="scan('vin')"></i></mu-text-field>

    <mu-text-field v-show="isShowRFID" v-model="bindRfid" placeholder="RFID" ref="rfid" class='input' @keyup.enter.native="setBindRfid()"><i class="iconfont icon-saomiao" @click="scan('rfid')"></i></mu-text-field>

    <mu-text-field v-show="isShowConfig" v-model="config" placeholder="配置" ref="config" class='input' @keyup.enter.native="getConfig()"><i class="iconfont icon-saomiao" @click="scan('config')"></i></mu-text-field>

    <mu-paper class="paper" :z-depth="2" v-show="isShowCard" >
        <div class="list-content">VIN ：<span>{{vin}}</span></div>
        <div class="list-content">车型：<span>{{carData.car}}</span><em class="space"></em>颜色：<span>{{carData.color}}</span></div>
        <div class="list-content">类型：<span>{{carData.carType}}</span></div>
        <div class="list-content">是否融资车：<span>{{carData.beKunnr}}</span></div>
        <div class="list-content">库位：<span class="library-position">{{carData.location}}</span></div>
    </mu-paper>

    <mu-paper class="msg" :z-depth="2" v-show="isShowMsg">
        {{msg}}
    </mu-paper>

    <div class="btn">
        <mu-button large :disabled="isDisabledGetTask" color="primary" @click="carAbnormal()">车辆异常</mu-button>
        <mu-button large :disabled="isDisabledDone" color="primary" @click="isDone()">确认完成</mu-button>
        <!-- <mu-button large :disabled="isDisabledDone" color="primary" @click="done('MANUAL')">确认完成</mu-button> -->
    </div>
    <mu-dialog title="是否确认完成?" width="600" max-width="80%" :esc-press-close="false" :overlay-close="false" :open.sync="isuredoneDialog">
        <mu-button slot="actions" flat color="primary" @click="sureDone()">是</mu-button>
        <mu-button slot="actions" flat color="primary" @click="closeThisConfirm">否</mu-button>
    </mu-dialog>
    <div class="targetLocation" ref="test" @click="watchTest">
        当前库位坐标
        <div>经：{{longitude}}</div>
        <div>纬：{{latitude}}</div>
        <div>半径：{{railRadius}}</div>
        <div>距离：{{lengths}}</div>
    </div>
    <scanning v-if="isScanning" :mark="scanMark" v-on:childByValue="childByValue" v-on:closeing="closeing"/>
  </div>
</template>

<script>
import myHead from '@/components/header'
import scanning from "@/components/scanning"
import api from "@/common/api"
export default {
  name: 'pickcar',
  components: {
    myHead, scanning
  },
  data () {
    return {
        scanMark: '',
        isScanning: false,
        iswatchTest: false,
        isuredoneDialog: false,
        vin: "",
        config: "",
        bindRfid: "",
        isShowRFID: false,
        isShowVin: false,
        isShowConfig: false,
        isShowCard: false,
        isDisabledGetTask: false,
        isDisabledDone: true,
        carData: {
            car: "",
            color: "",
            carType: "",
            beKunnr: "",
            location: ""
        },
        isShowMsg: false,
        msg: "",
        targetLocationX: null,
        targetLocationY: null,
        railRadius: 10,
        lengths: 0,
        watchMarks: null, //监听定位
        latitude: 0,
        longitude: 0,
        isDisCompute: true, // 是否调用电子围栏
        requestOnce: true
    }
  },
  methods: {
    closeing (val) {
      val ? this.isScanning = false : null;
    },
    childByValue (val) {
      if(val){
        if(val.split('&')[1] == 'vin'){
          this.vin = val.split('&')[0];
          this.getVin();
        }else if(val.split('&')[1] == 'config'){
          this.config = val.split('&')[0];
          this.getConfig();
        }else if(val.split("&")[1] == 'rfid'){
          this.bindRfid = val.split('&')[0];
          this.setBindRfid();
        }
      }
    },
    scan (txt) {
      this.scanMark = txt;
      this.isScanning = true;
    },
    watchTest(){
      if(this.iswatchTest){
        this.$refs.test.classList.remove('hover')
      }else{
        this.$refs.test.classList.add('hover')
      }
      this.iswatchTest = !this.iswatchTest;
    },
    isDone () {
        this.disCompute("MANUAL", ()=>{
            // 在电子围栏半径外
            this.isuredoneDialog = true;
        });
    },
    sureDone(){
        this.done("MANUAL");
        this.isuredoneDialog = false;
    },
    closeThisConfirm(){
        this.isuredoneDialog = false;
    },
    carAbnormal(){
        this.$router.push({name:'abnormal',params: {
            vin: this.vin,
            isShowRFID: this.isShowRFID}
        }) 
        // if(this.requestOnce){
        //     this.requestOnce = false;
        //     // manual 是否手动 MANUAL 手动 RAIL 电子围栏
        //     let data = Object.assign({},this.$store.state.user,{
        //         content: {
        //             vin : this.vin,
        //             configBarcode: this.config,
        //         }
        //     });
        //     /* 发送post请求 */
        //     this.common.reqData(api.app('carAbnormal'), data, res=>{
        //         console.log("完成返回数据", res);
        //         this.requestOnce = true;
        //         if(res.data.status == 100){
        //             // this.isDisabledDone = true;
        //             // this.isShowVin = false;
        //             // this.isShowConfig = false;
        //             // 提示
        //             this.Toast.success({
        //                 duration: 2000,
        //                 mask: true,
        //                 message: "回退成功"
        //             });
        //             // this.isDisCompute = false;
        //         }else{
        //             this.Toast({
        //                 message: res.data.msg
        //             });
        //         }
        //     },err =>{
        //         this.requestOnce = true;
        //         console.log(err)
        //     });
        // }else{
        //     return false;
        // }
    },
    done (manual) {
        if(this.requestOnce){
            this.requestOnce = false;
            // manual 是否手动 MANUAL 手动 RAIL 电子围栏
            let data = Object.assign({},this.$store.state.user,{
                content: {
                    vin : this.vin,
                    configBarcode: this.config,
                    action: manual
                }
            });
            /* 发送post请求 */
            this.common.reqData(api.app('pickCarDone'), data, res=>{
                console.log("完成返回数据", res);
                this.requestOnce = true;
                if(res.data.status == 100){
                    this.isDisabledDone = true;
                    this.isShowVin = false;
                    this.isShowConfig = false;
                    // 提示
                    this.Toast.success({
                        duration: 2000,
                        mask: true,
                        message: '收车成功'
                    });
                    this.isDisCompute = false;
                    manual == "RAIL" ? this.common.tts("任务已自动完成") : 0;
                    this.longitude = this.latitude = 0;

                    let isJump = res.data.content.isJump || "否";
                    let jumpPage = res.data.content.jumpPage || "";
                    let jumpVin = res.data.content.jumpVin || "";
                    
                    if(isJump === "是"){
                        if(jumpPage === "出库管理"){
                            this.$router.push({name:'outlibrary'});
                        }else if(jumpPage === "移位管理"){
                            this.$router.push({name:'transposing', params:{vin: jumpVin}});
                        }
                    }else{
                        this.$router.go(-1);
                    }
                }else{
                    this.Toast({
                        message: res.data.msg
                    });
                }
            },err =>{
                this.requestOnce = true;
                console.log(err)
            });
        }else{
            return false;
        }
    },
    setBindRfid(){
        let data = Object.assign({},this.$store.state.user,{
            content: {
                vin : this.vin,
                rfid: this.bindRfid
            }
        });
        this.Toast.loading({message: '绑定中...'});
        /* 发送post请求 */
        this.common.reqData(api.app('bindRfid'), data, res=>{
            console.log("rfid res", res);
            if(res.data.status == 100){
                this.isDisCompute = true;
                if(res.data.content.type == 'fail'){
                    this.Toast({
                        message: res.data.content.message
                    });
                }else{
                    this.isShowCard = true;
                    this.isDisabledDone = false;
                    this.carData.car = res.data.content.task.model;
                    this.carData.color = res.data.content.task.color;
                    this.carData.carType = res.data.content.task.carType;
                    this.carData.beKunnr = res.data.content.task.beKunnr ? res.data.content.task.beKunnr : '';
                    this.latitude = this.targetLocationX = res.data.content.task.targetLocationX;
                    this.longitude = this.targetLocationY = res.data.content.task.targetLocationY;
                    this.railRadius = res.data.content.task.railRadius;
                    this.carData.location = res.data.content.task.targetLocation;
                    // this.Toast({
                    //     message: "收车成功。"
                    // });
                    this.Toast.clear();
                }
            }else{
                this.Toast({
                    message: res.data.msg
                });
                // this.Toast.clear();
            }
        },err =>{
            console.log(err)
        });
    },
    getVin() {
        let data = Object.assign({},this.$store.state.user,{
            content: {
                vin : this.vin
            }
        });
        this.Toast.loading({message: '请求中...'});
        /* 发送post请求 */
        this.common.reqData(api.app('pickCarVinQuery'), data, res=>{
            console.log("VIN res", res);
            if(res.data.status == 100){
                this.Toast.clear();
                if(!res.data.content.task){
                    console.log('空');
                    this.isShowConfig = true;
                    setTimeout(() => {
                      this.$refs.config.$el.children[0].getElementsByTagName('input')[0].select();
                      window.plus ? plus.key.hideSoftKeybord() : 0;
                    }, 50);
                }else{
                    if(this.isShowRFID){
                        console.log(res);
                        this.bindRfid = res.data.content.rfId || "";
                        if(this.bindRfid){
                            this.setBindRfid();
                        }else{
                            this.$refs.rfid.$el.children[0].getElementsByTagName('input')[0].select();
                            window.plus ? plus.key.hideSoftKeybord() : 0;
                        }
                    }else{
                        this.isShowCard = true;
                        this.carData.car = res.data.content.task.model;
                        this.carData.color = res.data.content.task.color;
                        this.carData.carType = res.data.content.task.carType;
                        this.carData.beKunnr = res.data.content.task.beKunnr ? res.data.content.task.beKunnr : '';
                        this.pickCars(data);
                    }
                }
                this.isDisCompute = true;
            }else{
                this.Toast({
                    message: res.data.msg
                });
            }
        },err =>{
            console.log(err)
        });
    },
    pickCars(data){
        this.common.reqData(api.app('pickCarCreate'), data, res => {
            console.log("获取vin后收车数据", res)
            if(res.data.status == 100){
                this.latitude = this.targetLocationX = res.data.content.task.targetLocationX;
                this.longitude = this.targetLocationY = res.data.content.task.targetLocationY;
                this.railRadius = res.data.content.task.railRadius;
                this.carData.location = res.data.content.task.targetLocation;
                this.isDisabledDone = false;
            }else{
                this.Toast({
                    mask: true,
                    message: res.data.msg
                });
            }
        }, err =>{
            console.log(err)
        })
    },
    getConfig() {
        let data = Object.assign({},this.$store.state.user,{
            content: {
                vin : this.vin,
                configBarcode: this.config
            }
        });
        /* 发送post请求 */
        this.common.reqData(api.app('pickCarCreate'), data, res=>{
            console.log("配置卡返回数据", res);
            if(res.data.status == 100){
                this.isShowCard = true;
                this.carData.car = res.data.content.task.model;
                this.carData.color = res.data.content.task.color;
                this.carData.carType = res.data.content.task.carType;
                this.carData.beKunnr = res.data.content.task.beKunnr ? res.data.content.task.beKunnr : '';
                this.carData.location = res.data.content.task.targetLocation;
                this.isDisabledDone = false;
                this.targetLocationX = res.data.content.task.targetLocationX;
                this.targetLocationY = res.data.content.task.targetLocationY;
                this.railRadius = res.data.content.task.railRadius;
                this.isShowVin = this.isShowConfig = false;
            }else{
                // 提示
                this.Toast({
                    duration: 0,
                    mask: true,
                    message: res.data.msg
                });
            }
        },err =>{
            console.log(err)
        });
    },
    oneSearch () {
        // 带vin查询
        let datas = null;
        this.$route.params.vin ? datas = Object.assign({},this.$store.state.user,{
            content: {
                vin: this.$route.params.vin
            }
        }) : datas = this.$store.state.user;
        /* 发送post请求 */
        this.common.reqData(api.app('pickCarInfo'), datas, res=>{
            console.log("查询任务res", res);
            // this.isShowRFID = window.localStorage.getItem('beDriverBindCard') == 'false' ? false : true;
            // console.log(this.isShowRFID);
            if(res.data.status == 100){
                this.isShowRFID = res.data.content && res.data.content.beDriverBindCard || false;
                if(!res.data.content.task){
                    // 无任务
                    this.isDisabledDone = true;
                    this.isShowVin = true;
                    setTimeout(() => {
                        this.$refs.vin.$el.children[0].getElementsByTagName('input')[0].focus();
                        window.plus ? plus.key.hideSoftKeybord() : 0;
                    }, 50);
                }else{
                    // 有任务
                    this.isShowCard = true;
                    this.vin = res.data.content.task.vin;
                    this.carData.car = res.data.content.task.model;
                    this.carData.color = res.data.content.task.color;
                    this.carData.carType = res.data.content.task.carType;
                    this.carData.beKunnr = res.data.content.task.beKunnr ? res.data.content.task.beKunnr : '';
                    this.carData.location = res.data.content.task.targetLocation;
                    res.data.content.task.targetLocation ? this.isDisabledDone = false : this.isDisabledDone = true;
                    this.targetLocationX = res.data.content.task.targetLocationX;
                    this.targetLocationY = res.data.content.task.targetLocationY;
                    this.railRadius = res.data.content.task.railRadius;
                }
            }else{
                // 提示
                this.Toast({
                    duration: 0,
                    mask: true,
                    message: res.data.msg
                });
            }
        },err =>{
            console.log(err)
        });
    },
    disCompute (manual, func) {
        console.log('定位或速度已经改变')
        if(this.isDisCompute){
            this.common.distanceCompute({
                latitude: this.targetLocationX,
                longitude: this.targetLocationY
            },{
                latitude: this.$store.state.latitude,
                longitude: this.$store.state.longitude
            }, this.railRadius, ()=>{
                // 在电子围栏半径内
                this.done(manual)
            }, func);
            // 测试用距离计算 //
            let _this = this;
            this.latitude = this.targetLocationX;
            this.longitude = this.targetLocationY;
            let selfPoint = new plus.maps.Point(this.longitude, this.latitude)
            let targetPoint = new plus.maps.Point(this.$store.state.longitude, this.$store.state.latitude)
            plus.maps.Map.calculateDistance(targetPoint, selfPoint, function (event) {
                var distance = event.distance // 转换后的距离值
                _this.lengths = distance
            }, function (e) {
                console.log('Failed:' + JSON.stringify(e))
            })
        }
    }
  },
  mounted () {
    // 进入页面第一次请求
    // !this.$route.params.vin ? this.oneSearch() : this.vin = this.$route.params.vin,this.getVin();
    this.oneSearch();
  },
  computed: {
    latitudeChange () {
        return this.$store.state.latitude;
    },
    longitudeChange () {
        return this.$store.state.longitude;
    },
    speedChange () {
        return this.$store.state.speed;
    }
  },
  watch:{
    latitudeChange: function(data) {
        this.disCompute("RAIL");
    },
    longitudeChange: function(data) {
        this.disCompute("RAIL");
    },
    speedChange: function(data) {
        this.disCompute("RAIL");
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.pickcar{
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    position: absolute;
}
.input{
    display: block;
    margin: 15px auto;
    width: 85%;
}
.paper, .state, .msg{
    width: 85%;
    margin: 4em auto 0;
    padding: 1.5em 0;
}
.state, .msg{
    text-align: center;
    color: red;
    font-size: 1em;
}
.list-content{
    padding: 8px 20px;
}
.library-position{
    font-size: 2.2em;
    font-weight: bold;
    color: red;
    text-shadow: 2px 2px 5px rgba(0,0,0,0.5);
}
.space{
    padding: 0 20px;
}
.btn{
  position: absolute;
  bottom: 10px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
}
.btn .mu-raised-button{
  font-size: 18px;
  height: 40px;
  line-height: 40px;
}
</style>
